package br.com.condominio.view.beans;

import java.io.IOException;
import java.sql.SQLException;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpSession;

import br.com.condominio.controller.LoginController;
import br.com.condominio.view.vo.LoginVO;

@ManagedBean(name = "loginMBean")
@SessionScoped
public class LoginMBean {

	// Controller para acesso ao DAO
	private final LoginController controller;
	private LoginVO loginVO = new LoginVO();

	public LoginMBean() throws ClassNotFoundException, SQLException {
		controller = new LoginController();
	}

	public LoginVO getLoginVO() {
		return loginVO;
	}

	public void setLoginVO(LoginVO loginVO) {
		this.loginVO = loginVO;
	}

	public void validaLogin() throws SQLException, ClassNotFoundException {
		try {
			if (controller.validaLogin(this.loginVO)) {
				loginVO.setLogado(true);
				FacesContext.getCurrentInstance().getExternalContext()
						.redirect("/GateSystem/index.jsf");
			} else {
				loginVO.setLogado(false);
				FacesContext.getCurrentInstance().getExternalContext()
						.redirect("/GateSystem/login/login.jsf");
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public String logout() {
		loginVO = new LoginVO();
		loginVO.setLogado(false);
		try {
			HttpSession sessao = (HttpSession) FacesContext
					.getCurrentInstance().getExternalContext()
					.getSession(false);
			sessao.invalidate();
			FacesContext.getCurrentInstance().getExternalContext()
					.redirect("/GateSystem/login/login.jsf");
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
}
